package com.filetransfer.domain;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import com.filetransfer.filemanager.util.FileUtil;

public class FileInfoHolder implements Serializable {

	/**
	 *
	 */
	private static final long serialVersionUID = -3646608851335206827L;

	private String fileDir;
	private File mainFileDir;

	private List<FileInfo> fileInfoSet = new ArrayList<FileInfo>();
	private boolean servingFileManager = false;

	/**
	 *
	 * @param path
	 * @param isFileManager - boolean - set to true if being used in filemanager, to calculate chunk sizes etc.
	 * @throws Exception
	 */
	public FileInfoHolder(String path, boolean isFileManager) throws Exception{
		fileDir = path;
		servingFileManager = isFileManager;
		mainFileDir = new File(fileDir);

		if(!mainFileDir.canRead() || !mainFileDir.isDirectory()){
			throw new Exception("Invalid fileDir specified. Please check and restart the program with the correct fileDir parameter.");
		}
	}


	public List<FileInfo> getFileInfoList(boolean reload){
		if(reload){
			loadFileInfoList();
		}
		return fileInfoSet;
	}



	/**
	 * Used for sending the list of file info objects with
	 * basic information such as file name and size.
	 * Clears the infoList every time invoked. When invoked by
	 * the filemanager, also calculates the chunk size and number of chunks
	 * @return
	 */
	public void loadFileInfoList(){
		FileInfo info;
		fileInfoSet.clear();

		File[] fileList = mainFileDir.listFiles();
		if(fileList != null){
			for(File temp:fileList){
				// load only files. if there are directories/ignore them
				if(temp.canRead() && temp.isFile()){
					info = new FileInfo(temp.getName(),temp.length());
					if(servingFileManager){
						info = FileUtil.calculateChunkDetails(info);
					}
					fileInfoSet.add(info);
				}
			}
		}
	}



}
